package com.zyz.N_反射机制.基本应用.调用运行时类的指定结构;

import java.lang.reflect.Field;

/**
 * @author: vick
 * @Date: 2025/4/14
 * @Description:
 * @version: 1.0
 */
public class Test1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        //1. 获取Student的Class对象
        Class<?> aClass = Class.forName("com.vick.N_反射机制.基本应用.调用运行时类的指定结构.Student");

        //2. 获取属性对象
        Field field = aClass.getDeclaredField("id");

        //3. 创建对象
        Object stu = aClass.newInstance();

        //4. 如果id是私有的，在当前类中不可访问
        field.setAccessible(true);

        //5. 获取属性值
        Object value = field.get(stu);
        System.out.println("id = " + value);

        //6. 设置属性值
        field.set(stu, 2);

        value = field.get(stu);
        System.out.println("id = " + value);
    }
}
